import * as vscode from 'vscode';
import { BaseLLM } from "../../../core/llm/baseLLM"
import { ChatMessage } from '../../../core';
import { VerticalDiffManager } from '../../../src/diff/vertical/manager';
import { LLMFactory } from '../../../core/llm/llmFactory';
import { ProxyService } from '../../../src/services/proxyService';
import { checkLoginStatus } from '../../utils/authGuard';
import { AnalyticsService } from '../../../src/services/analyticsService';


function getRange(stratLine0:number, endLine0:number): vscode.Range {
    const startLine = Math.min(stratLine0, endLine0);
    const endLine = Math.max(stratLine0, endLine0);
    return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
}

/**
 * Removes common leading whitespace from all lines of a code snippet
 * and trims extra whitespace from the beginning and end
 */
function removeIndentation(text: string): string {
    if (!text) return text;
    
    // Split into lines
    let lines = text.split('\n');
    
    // Trim empty lines from the beginning and end
    while (lines.length > 0 && lines[0].trim() === '') {
        lines.shift();
    }
    while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
        lines.pop();
    }
    
    if (lines.length === 0) return '';
    
    // Find minimum indentation across non-empty lines
    const minIndent = lines
        .filter(line => line.trim().length > 0)
        .reduce((min, line) => {
            const match = line.match(/^(\s*)/);
            const indent = match ? match[0].length : 0;
            return Math.min(min, indent);
        }, Infinity) || 0;
    
    // Remove the common indentation from each line
    return lines.map(line => {
        return line.slice(minIndent);
    }).join('\n');
}


export async function addComment(verticalDiffManager: VerticalDiffManager, llmFactory: LLMFactory, context: vscode.ExtensionContext) {
    // 检查登录状态
    const isLoggedIn = await checkLoginStatus(context);
    if (!isLoggedIn) {
        return;
    }

    AnalyticsService.getInstance(context).trackEvent('addComment');

    // 调用api得到llm，可直接使用，llm-Name区分实例化
    let llm: BaseLLM|undefined = llmFactory.getLLM("deepseek-chat");
    if (!llm) {
        vscode.window.showErrorMessage("LLM not found");
        return;
    }

    let editor = vscode.window.activeTextEditor;
    if (!editor) {
        return undefined;
    }
    let startLine, endLine: number;
    startLine = editor.selection.start.line;
    endLine = editor.selection.end.line;
    let selectedRange = getRange(startLine, endLine);
    let highlighted = editor.document.getText(selectedRange);
    
    // Remove common indentation from the highlighted code
    highlighted = removeIndentation(highlighted);

    // Check if highlighted code is empty
    if (!highlighted || highlighted.trim() === '') {
        vscode.window.showInformationMessage("Please select some code to add comments");
        return;
    }
    // Get user's language configuration
    const config = vscode.env.language;

    const text = 'write comments for this code,only add comments and do not modify the original code;If there are sufficient comments in the code, please return to the original code directly';
    // Set content based on language
    const contentText = config.startsWith('zh') ? vscode.l10n.t(text) : text;

    const prompt: ChatMessage[] = [
        {role: "user", content: contentText},
        {role: "user", content: highlighted},
      ];

    verticalDiffManager.streamEdit(ProxyService.getInstance(context)._streamChat(prompt, new AbortController().signal));
}